package rexsee.device;

import java.util.Locale;

import rexsee.core.browser.Browser;
import rexsee.core.browser.clazz.JavascriptInterface;
import android.content.Context;

public class RexseeLocale implements JavascriptInterface {

	public static final String INTERFACE_NAME = "Locale";
	@Override
	public String getInterfaceName() {
		return mBrowser.application.resources.prefix + INTERFACE_NAME;
	}
	@Override
	public JavascriptInterface getInheritInterface(Browser childBrowser) {
		return this;
	}
	@Override
	public JavascriptInterface getNewInterface(Browser childBrowser) {
		return new RexseeLocale(childBrowser);
	}

	private final Context mContext;
	private final Browser mBrowser;
	public RexseeLocale(Browser browser) {
		super();
		mBrowser = browser;
		mContext = browser.getContext();
	}

	//JavaScript Interface

	public String getDisplayName() {
		return mContext.getResources().getConfiguration().locale.getDisplayName();
	}
	public String getCountry() {
		return mContext.getResources().getConfiguration().locale.getCountry();
	}
	public String getDisplayCountry() {
		return mContext.getResources().getConfiguration().locale.getDisplayCountry();
	}
	public String getLanguage() {
		return mContext.getResources().getConfiguration().locale.getLanguage();
	}
	public String getDisplayLanguage() {
		return mContext.getResources().getConfiguration().locale.getDisplayLanguage();
	}
	public String getVariant() {
		return mContext.getResources().getConfiguration().locale.getVariant();
	}
	public String getDisplayVariant() {
		return mContext.getResources().getConfiguration().locale.getDisplayVariant();
	}
	public String getISO3Country() {
		return mContext.getResources().getConfiguration().locale.getISO3Country();
	}
	public String getISO3Language() {
		return mContext.getResources().getConfiguration().locale.getISO3Language();
	}

	public String getAvailableLanguages() {
		String[] l = Locale.getISOLanguages();
		String rtn = "";
		for (int i = 0; i < l.length; i++) {
			rtn += (i == 0) ? "\"" + l[i] + "\"" : ",\"" + l[i] + "\"";
		}
		return "[" + rtn + "]";
	}
	public String getAvailableCountries() {
		String[] l = Locale.getISOCountries();
		String rtn = "";
		for (int i = 0; i < l.length; i++) {
			rtn += (i == 0) ? "\"" + l[i] + "\"" : ",\"" + l[i] + "\"";
		}
		return "[" + rtn + "]";
	}
	public void setLanguage(String lang) {
		Locale[] l = Locale.getAvailableLocales();
		for (int i = 0; i < l.length; i++) {
			if (l[i].getLanguage().equalsIgnoreCase(lang)) {
				Locale.setDefault(l[i]);
				mContext.getResources().getConfiguration().locale = l[i];
				return;
			}
		}
		mBrowser.exception(getInterfaceName(), "Language not found: " + lang);
	}

}
